package org.jupiter.blog.common.utils;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.security.MessageDigest;

public class PasswordEncryptUtil {

	// === RSA 解密（前端公钥加密，后端私钥解密） ===
	public static String rsaDecrypt(String encryptedData) {
		try{
			// 这里需要配置你自己的 RSA 私钥
			String privateKeyPem = "-----BEGIN PRIVATE KEY-----\nYOUR_PRIVATE_KEY\n-----END PRIVATE KEY-----";
			privateKeyPem = privateKeyPem
					.replace("-----BEGIN PRIVATE KEY-----", "")
					.replace("-----END PRIVATE KEY-----", "")
					.replaceAll("\\s+", "");

			byte[] keyBytes = Base64.getDecoder().decode(privateKeyPem);
			PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
			KeyFactory kf = KeyFactory.getInstance("RSA");
			PrivateKey privateKey = kf.generatePrivate(spec);

			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			byte[] decodedData = Base64.getDecoder().decode(encryptedData);
			byte[] decrypted = cipher.doFinal(decodedData);
			return new String(decrypted, StandardCharsets.UTF_8);
		} catch (Exception e){
			throw new RuntimeException("RSA解密失败", e);
		}
	}

	// === 数据库存储加密（SHA-256 + 盐） ===
	public static String dbEncrypt(String plainPassword) {
		try{
			String salt = "JUPITER_BLOG_SALT"; // 可以改成随机盐+存库方式更安全
			MessageDigest digest = MessageDigest.getInstance("SHA-256");
			byte[] hash = digest.digest((plainPassword + salt).getBytes(StandardCharsets.UTF_8));
			return Base64.getEncoder().encodeToString(hash);
		} catch (Exception e){
			throw new RuntimeException("密码加密失败", e);
		}
	}
}
